from app.app_init import app
from flask_login import login_required
from flask import render_template, flash, redirect, url_for, request, send_from_directory
from forms.article_form import ArticleForm
from forms.image_upload_form import ImageUploadForm
from models import article
from services import article_service
from services.image_service import ImageService


@app.route('/createarticle.html', methods=['GET', 'POST'])
@login_required
def create_article_page():
    form = ArticleForm()
    if form.validate_on_submit():
        new_article = article.Article()
        new_article.title = form.title.data
        new_article.content = form.content.data
        res = article_service.ArticleService().create_article(new_article)
        if res:
            flash('文章发布成功', category='success')
            return redirect(url_for('home_page'))
        else:
            flash('文章发布失败,请检查', category='danger')
    return render_template('editarticle.html', form=form, is_edit=False)


@app.route('/editarticle/<article_id>.html',methods=['GET', 'POST'])
@login_required
def edit_article_page(article_id):
    form = ArticleForm()
    if request.method =='GET':
        current_article = article_service.ArticleService().get_article(article_id)
        form.title.data = current_article.title
        form.content.data = current_article.content
        return render_template('editarticle.html', form=form, is_edit=True)
    if form.validate_on_submit():
        new_article = article.Article()
        new_article.id = article_id
        new_article.title = form.title.data
        new_article.content = form.content.data
        res = article_service.ArticleService().update_article(new_article)

    return redirect(url_for('article_page', article_id=article_id))


@app.route('/images.html', methods=['GET', 'POST'])
@login_required
def images_page():
    form = ImageUploadForm()
    if form.validate_on_submit():
        ImageService().upload_image(form.image_file.data)

    image_filenames = ImageService().get_image_name_list()

    return render_template('images.html', form=form, image_filenames=image_filenames)

@app.route('/image/<image_name>')
@login_required
def show_image(image_name):
    image_full_path = ImageService.get_image_file_fullname(image_name)
    if not image_full_path.exists():
        pass
    return send_from_directory(ImageService.get_image_dir(), image_name)
